<!-- 
	/**
	 * All rights Reserved, Designed By www.youyacao.com <br>
	 * @Description:上传视频页面 <br>
	 * @version 蜻蜓Q系统  <br>
	 * @author:成都市一颗优雅草科技有限公司  <br>
	 * 注意：使用我司开源源代码请遵循license文件的协议仅供个人非盈利使用，禁止用于其他的商业用途
	 * 需要商业用途或者定制开发等可访问songshu.youyacao.com  联系QQ:2853810243 422108995 23625059584
	 * 正版系统查询系统 zhengbancha.youyacao.com
	 */
 -->
<template>
	<view class="body">
		<view class="upload-section">
			<view class="video-box" @tap="_chooseVideo">
				<video class="video" id="video" :src="src" v-if="src" :controls="false" autoplay></video>
				<image class="add-icon" src="/static/images/add-icon_white.png" mode="" v-else></image>
			</view>
			<view class="progress-box" v-if="uploadProgress">
				<view class="progress-text">{{ duration_str }}</view>
			</view>
		</view>
		<view class="input-section">
			<textarea class="textarea" placeholder="请输入标题~" v-model="title" />
			<view class="select" @tap="show = true">
				<view class="select-left">
					<image class="select-left__right" src="/static/icon-fenlei.png" mode=""></image>
					<text>{{ selectItem.label }}</text>
				</view>
				<image class="select-icon" src="/static/images/right-arrow.png" mode=""></image>
			</view>
			<view class="price-input">
				<view class="price-input__text">视频价格（默认免费）</view>
				<u-input v-model="price" type="number" border placeholder="请填入视频价格" style="border-color: #eee;" />
			</view>
			<view class="progress-view" v-if="uploadProgress">
				<u-line-progress :round="false" height="24" :percent="uploadProgress"></u-line-progress>
			</view>
		</view>
		<view class="btn-box">
			<u-button type="success" @click="_verify" :loading="loading"
				style="background-color: #0862EC;">发布</u-button>
		</view>
		<u-select v-model="show" mode="mutil-column-auto" :list="list" @confirm="_confirm"></u-select>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
import { Categories, ReleaseVideo, getQtToken } from '@/common/api.js'
import { BASE_URL } from '@/common/config.js'
import { getToken } from '@/common/common.js'
import VTabbar from '@/components/v-tabbar/v-tabbar.nvue'
import { mapActions } from 'vuex'
import Test from '@/common/test.js'
import moment from 'moment'

export default {
	data() {
		return {
			price: '',
			video: {},
			src: '',
			show: false,
			list: [],
			selectItem: {
				value: '',
				label: '选择分类'
			},
			title: '',
			loading: false,
			uploadProgress: 0,
			videoContext: null,
			machineResult: {
				Normal: "正常",
				Polity: "涉政",
				Sex: "色情",
				Terror: "暴恐",
				Legal: "违法违规",
				Ad: "广告"
			},
			testing: false,
			duration: '',
			duration_str: ''
		};
	},
	components: { VTabbar },
	onLoad() {
		this._getCategories()

	},
	onShow() {
		if (this.videoContext) {
			this.videoContext.play()
		}
		// this.updateUserinfo()
	},
	methods: {
		...mapActions(['updateUserinfo']),
		_chooseVideo() {
			uni.chooseVideo({
				count: 1,
				sourceType: ['camera', 'album'],
				compressed: false,
				success: (res) => {
					this.duration = res.duration
					const h = moment.duration(this.duration * 1000).hours()
					const m = moment.duration(this.duration * 1000).minutes()
					const s = moment.duration(this.duration * 1000).seconds()

					const _h = h > 10 ? h : '0' + h
					const _m = m > 10 ? m : '0' + m
					const _s = s > 10 ? s : '0' + s

					this.duration_str = `${_h}:${_m}:${_s}`
					this.src = res.tempFilePath
					this.videoContext = uni.createVideoContext('video', this)
					this._uploadVideo()
				}
			})
		},
		_getCategories() {
			Categories().then(({ code, data }) => {
				if (code === 200) {
					data.map((item, index) => {
						this.list.push({
							value: item.id,
							label: item.name,
							children: []
						})
						if (item.children.length) {
							item.children.map(item => {
								this.list[index].children.push({
									value: item.id,
									label: item.name
								})
							})
						} else {
							this.list[index].children[0] = {
								value: item.id,
								label: item.name
							}
						}
					})
				}
			})
		},
		_confirm(e) {
			this.selectItem = e[1]
		},
		_submit() {
			// if (this.testing) {
			// 	return uni.showToast({
			// 		title: '视频内容安全检测中...',
			// 		icon: 'none'
			// 	})
			// }
			this.loading = true
			ReleaseVideo({
				category_id: this.selectItem.value,
				title: this.title,
				thumb: this.video.img_url,
				video_url: this.video.url,
				duration: this.duration,
				price: this.price
			}).then(({ code, msg }) => {
				uni.showToast({
					title: msg,
					icon: 'none'
				})
				this.loading = false
				if (code === 200) {
					this.title = ''
					this.src = ''
					this.video = {}
					setTimeout(() => {
						this.uploadProgress = 0
					}, 200)
					this.selectItem = {
						value: '',
						label: '选择分类'
					}
				}
			}).catch(err => {
				this.loading = false
			})
		},
		_verify() {
			if (!this.title) {
				return this.$refs.uToast.show({
					title: '请输入标题',
					type: 'warning'
				})
			}
			if (!this.src) {
				return this.$refs.uToast.show({
					title: '请选择视频',
					type: 'warning'
				})
			}
			if (!this.selectItem.value) {
				return this.$refs.uToast.show({
					title: '请选择分类',
					type: 'warning'
				})
			}
			if (this.uploadProgress === 100) {
				this.loading = true
				this._checkText(this.title)
			} else {
				uni.showToast({
					title: '请等待文件上传完成',
					icon: 'none'
				})
			}
		},
		_checkText(content) {
			Test('text', content).then(({ machine_result }) => {
				if (machine_result === 'Normal') {
					this._submit()
				} else {
					const msg = this.machineResult[machine_result]
					uni.showToast({
						title: `检测到您的文字内容涉及${msg}，请重新输入。`,
						icon: 'none'
					})
					this.loading = false
					this.title = ''
				}
			})
		},
		_uploadVideo() {
			// const uploadTask = uni.uploadFile({
			// 	url: `${BASE_URL}uploadVideo`,
			// 	header: {
			// 		authorization: getToken()
			// 	},
			// 	filePath: this.src,
			// 	name: 'file',
			// 	formData: {},
			// 	success: (uploadFileRes) => {
			// 		const { code, msg, data } = JSON.parse(uploadFileRes.data)
			// 		console.log(data)
			// 		if (code === 200) {
			// 			this.video = data
			// 			// this._checkVideo(data.url)
			// 		} else {
			// 			uni.showToast({
			// 				title: msg,
			// 				icon: 'none'
			// 			})
			// 		}
			// 	},
			// 	fail: (err) => {
			// 		console.log('视频上传失败', err)
			// 	}
			// })
			// uploadTask.onProgressUpdate((res) => {
			// 	this.uploadProgress = res.progress
			// })
			var date = new Date();
			getQtToken({}).then((res) => {
				//如果获取成功
				if (res.code == 200) {

					let token = res.data.token;
					var date = new Date();
					//开始上传
					const uploadTask = uni.uploadFile({
						url: 'https://upload-z2.qiniup.com',
						filePath: this.src,
						dataType: 'json',
						name: 'file',
						formData: {
							'token': token,
							'key': 1 + "/" + date.getTime() + "." + 'mp4'
						},
						success: (res) => {

							uni.hideLoading()
							this.uploadFile = false;
							this.progress = 0;
							if (res.statusCode == 200) {
								var data = JSON.parse(res.data);
								if (!data.key) {
									uni.showToast({
										title: '上传失败,' + data.error,
										icon: 'none'
									});
									return;
								}
								uni.showToast({
									title: '上传成功',
								});
								this.video.url = 'https://qingtingcun.youyacao.com/' + data.key
								// this._checkImage(this.config.domain + data.key)
							}
						},
						fail(e) { }
					});
					uploadTask.onProgressUpdate((res) => {
						this.uploadProgress = res.progress
					});
				}
			})

		},
		_checkVideo(content) {
			this.testing = true
			Test('video', content).then(({ machine_result }) => {
				this.testing = false
				if (machine_result !== 'Normal') {
					const msg = this.machineResult[machine_result]
					uni.showToast({
						title: `检测到您的视频涉及${msg}，请重新选择。`,
						icon: 'none'
					})
					this.src = ''
					this.video = {}
					this.uploadProgress = 0
				}
			}).catch(err => {
				this.testing = false
			})
		}
	},
	onHide() {
		if (this.videoContext) {
			this.videoContext.pause()
		}
	}
}
</script>

<style lang="scss" scoped>
.body {
	background-color: #fff;
	min-height: 100vh;
	padding-bottom: 120rpx; // 给底部按钮留空间
	display: flex;
	flex-direction: column;
	align-items: center;
}

.upload-section {
	width: 90vw;
	max-width: 700rpx;
	margin: 40rpx auto 24rpx auto;
	background: #fff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 24rpx rgba(0,0,0,0.06);
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 32rpx 0 24rpx 0;
}

.video-box {
	width: 220rpx;
	height: 220rpx;
	border-radius: 12rpx;
	background-color: #f7f7f7;
	display: flex;
	align-items: center;
	justify-content: center;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
	margin-bottom: 16rpx;
}

.video {
	width: 100%;
	height: 100%;
	border-radius: 12rpx;
}

.add-icon {
	width: 60rpx;
	height: 60rpx;
}

.progress-box {
	width: 180rpx;
	text-align: center;
	margin-bottom: 8rpx;
}

.progress-text {
	font-size: 26rpx;
	color: #888;
	margin-top: 12rpx;
}

.input-section {
	width: 90vw;
	max-width: 700rpx;
	background: #fff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 24rpx rgba(0,0,0,0.06);
	padding: 32rpx 24rpx 16rpx 24rpx;
	margin-bottom: 24rpx;
}

.textarea {
	width: 100%;
	min-height: 50rpx;
	color: #333;
	background: #f7f7f7;
	border-radius: 8rpx;
	padding: 16rpx;
	border: 1rpx solid #eee;
	font-size: 30rpx;
	margin-bottom: 24rpx;
	box-sizing: border-box;
}

.select {
	height: 80rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	color: #222;
	font-size: 28rpx;
	background: #f7f7f7;
	border-radius: 8rpx;
	margin-bottom: 24rpx;
	box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
	padding: 0 24rpx;
}

.select-left {
	display: flex;
	align-items: center;
	color: #222;
}

.select-left__right {
	width: 45rpx;
	height: 45rpx;
	margin-right: 12rpx;
}

.select-icon {
	width: 40rpx;
	height: 40rpx;
}

.price-input {
	margin-bottom: 24rpx;
	.price-input__text {
		color: #222;
		margin-bottom: 16rpx;
		font-size: 28rpx;
	}
}

.line {
	margin: 0 0 32rpx 0;
	height: 1rpx;
	background-color: #eee;
}

.progress-view {
	padding: 0 0 24rpx 0;
}

.btn-box {
	position: fixed;
	right: 0;
	bottom: 0;
	left: 0;
	padding: 32rpx 32rpx 40rpx 32rpx;
	background: #fff;
	box-shadow: 0 -2rpx 16rpx rgba(0,0,0,0.04);
	z-index: 10;
}

.u-button {
	width: 100%;
	font-size: 32rpx;
	border-radius: 12rpx;
}

@media (max-width: 500px) {
	.upload-section, .input-section {
		width: 98vw;
		max-width: none;
		padding-left: 8rpx;
		padding-right: 8rpx;
	}
}
</style>
